package com.cloud.lan.service.task;

import com.cloud.lan.entity.constant.WxDataConstant;
import com.cloud.lan.service.tx.wx.WxAccessTokenService;
import com.cloud.lan.service.tx.wx.config.WxMaConfiguration;

import com.cloud.lan.service.tx.wx.config.WxMpConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

/**
 * 定时任务
 * @author ErKang
 * @date Created in 2022/1/6 01:06
 * @title TestTask.java
 * Department: Product development
 */
@Component
@Configuration
@Slf4j
@EnableScheduling
public class WxTask {
@Value("${spring.profiles.active}")
    private String active;
    @Resource
    WxMaConfiguration wxMaConfiguration;
    @Resource
    WxMpConfiguration wxMpConfiguration;
    @Resource
    WxAccessTokenService wxAccessTokenService;

    @PostConstruct
    public void initWxTk() {
        checkWxAccessTokenTask();
    }

    /**
     * 每60分钟执行一次
     * 判断环境只是针对一个环境做新的获取
     */
    @Scheduled(cron = "0 0/60 * * * ?")
    private void checkWxAccessTokenTask() {
        if (!"prod".equals(active)) {
            log.warn("# checkWxAccessTokenTask not env prod");
            return;
        }
        try {
            String accessToken = wxAccessTokenService.get(WxDataConstant.APPID);
            log.info("#定时任务 checkWxAccessTokenTask {} ", accessToken);
            wxMaConfiguration.reFreshWXTk(WxDataConstant.APPID);
            String mpAccessToken = wxAccessTokenService.get(WxDataConstant.MPAPPID);
            log.info("#定时任务 checkWxMpAccessTokenTask {} ", mpAccessToken);
            wxMpConfiguration.reFreshWXTk(WxDataConstant.MPAPPID);
        } catch (Exception e) {
            log.error("#定时任务 错误 :", e);
        }
    }
}
